package thread;

import java.util.Scanner;

/**
 * wait() 和 notify() 测试
 * wait 需要搭配 synchronized 关键字使用, 而 sleep 不需要
 * 1. wait()方法会释放锁, 让出CPU资源, 线程进入等待状态
 * 2. notify()方法会唤醒一个正在等待的线程, 线程进入就绪状态
 * 3. wait()和notify()方法只能由锁对象调用
 */
public class demo20 {
    public static void main(String[] args) {
        Object locker = new Object();
        Thread t1 = new Thread(() -> {
            synchronized (locker) {
                System.out.println("wait 之前");
                try {
                    locker.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("wait 之后");
            }
        });

        Thread t2 = new Thread(() -> {
            synchronized (locker) {
                System.out.println("notify 之前");
                Scanner scanner = new Scanner(System.in);
                System.out.println("请输入任意字符唤醒: ");
                scanner.next();
                locker.notify();
                System.out.println("notify 之后");
            }
        });

        t1.start();
        t2.start();
    }
}
